import React from 'react';
import { usePersistFn } from 'ahooks';

export interface IPromiseLoadingConfig {
  // 默认 loading
  defaultLoading?: boolean;
}

/**
 * 自动处理 AsyncFunction loading 的 hooks
 */
export default function usePromiseLoading<F extends (...args: any[]) => Promise<any> | void>(
  func: F,
  config?: IPromiseLoadingConfig,
): [F, boolean | undefined] {
  const [loading, setLoading] = React.useState(config?.defaultLoading);

  const funcWrapper = usePersistFn(async (...args: any[]) => {
    if (!loading) {
      setLoading(true);
    }
    try {
      const result = await func(...args);
      setLoading(false);
      return result;
    } catch (e) {
      setLoading(false);
      throw e;
    }
  });

  return [funcWrapper as F, loading];
}
